package com.cin.cma.server.pos.config;

import com.corundumstudio.socketio.SocketIOClient;
import com.corundumstudio.socketio.SocketIOServer;
import com.corundumstudio.socketio.annotation.OnConnect;
import com.corundumstudio.socketio.annotation.OnDisconnect;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 *
 * @Date：2024-07-16 18:12
 */
@Slf4j
@Component
public class SocketIOHandler {
    private static Map<UUID, String> clientMap = new HashMap<>();
    @Autowired
    private SocketIOServer socketIoServer;

    //Spring IoC容器创建之后，在加载SocketIOService Bean之后启动
    //服务端启动
    @PostConstruct
    private void autoStartup() throws Exception {
        try {
            socketIoServer.start();
        } catch (Exception ex) {
            log.error("SocketIOServer启动失败");
        }
    }

    //Spring IoC容器在销毁SocketIOService Bean之前关闭,避免重启项目服务端口占用问题
    //服务端关闭
    @PreDestroy
    private void autoStop() throws Exception {
        socketIoServer.stop();
    }

    //客户端连接的时候触发
    @OnConnect
    public void onConnect(SocketIOClient client) {
        String cinemaLinkId = client.getHandshakeData().getSingleUrlParam("cinemaLinkId");
        SocketIOService.clientMap.put(cinemaLinkId, client);
        clientMap.put(client.getSessionId(), cinemaLinkId);
        //客户端:/127.0.0.1:64540  sessionId:9acac9ab-a000-43a7-bf97-31fac791e4f4 username: 张三已连接
        log.info("客户端:" + client.getRemoteAddress() + "  sessionId:" + client.getSessionId() + " cinemaLinkId:" + cinemaLinkId + "已连接");
    }

    //客户端关闭连接时触发
    @OnDisconnect
    public void onDisconnect(SocketIOClient client) {
        //客户端:9acac9ab-a000-43a7-bf97-31fac791e4f4断开连接
        SocketIOService.clientMap.remove(clientMap.get(client.getSessionId()));
        clientMap.remove(client.getSessionId());
        log.info("客户端:" + client.getSessionId() + "断开连接");

    }

}
